from ctypes.wintypes import tagPOINT
from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
# 认证模块
from django.contrib import auth
# 对应数据库
from django.contrib.auth.models import User
from django.contrib.auth import *
import requests
import json



# 登录
@require_http_methods(["GET"])
def login(request):
    response = {}
    try:
        body = json.loads(request.GET.get('body'))
        user = authenticate(
            username = body['account'], 
            password = body['password'],
        )
        if user is not None:
            response['body'] = body
            response['msg'] = 'success'
            response['error_num'] = 0
        else:
            response['msg'] = str('用户名或密码错误!')
            response['error_num'] = 1
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 注册
@require_http_methods(["GET"])
def register(request):
    response = {}
    try:
        body = json.loads(request.GET.get('body'))
        User.objects.create_user(
            username = body['username'],
            password = body['password'],
            email = body['email'], 
            first_name = body['name'],
            is_superuser = 0 
        )
        response['body'] = body
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
